package fun.diaoer.service.security;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import fun.diaoer.common.StringUtil;
import fun.diaoer.entity.vo.VDISysRole;
import fun.diaoer.entity.vo.VDISysUser;
import fun.diaoer.mapper.DISysUserMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Getter
@Setter
@Service
public class DiaoerUserDetailService implements UserDetailsService {
	
//	@Autowired
//	private AuthService authService;
	@Autowired
	private DISysUserMapper dISysUserMapper;
	
	private boolean isAdmin;

	 /**
     * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
     */

    @Override
    public DiaoerUserDetail loadUserByUsername(String username) throws UsernameNotFoundException {
    	if(StringUtil.isBlank(username)) {
    		return null;
    	}
    	VDISysUser sysUser = dISysUserMapper.searchUserInfoByUserNme(username,isAdmin);
        if (null == sysUser) {
            throw new UsernameNotFoundException(username);
        }
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        for (VDISysRole role : sysUser.getRoles()) {
        	authorities.add(new SimpleGrantedAuthority(role.getRoleCde()));
        }
        return new DiaoerUserDetail(sysUser.getUserName(), sysUser.getPassword(), authorities,sysUser.getRoles());
    }

}
